//
//  ZLSafeCodeKeyboard.swift
//  ZLSafeCodeKeyboard
//
//  Created by KDWL on 2023/1/10.
//

import UIKit

public typealias KDSafePWDBlock = (_ pwd: String) -> (Bool)

public class ZLSafeCodeKeyboard: UIViewController {
    public override var title: String? {
        didSet {
            self.titleLabel.text = title
        }
    }
    /// 完成
    var complete: KDSafePWDBlock?
    /// 密码
    var pwd: String = ""
    /// 底部主视图
    lazy var bottomView: UIView = {
        let view = UIView(frame: CGRect(x: 0, y: self.view.frame.size.height, width: self.view.frame.size.width, height: 376))
        view.backgroundColor = UIColor.white
        return view
    }()
    /// 标题
    lazy var titleLabel: UILabel = {
        let label = UILabel(frame: CGRect(x: 20, y: 22, width: self.view.frame.size.width, height: 22))
        label.text = "输入安全密码"
        label.textColor = UIColor.init(hex: "#030303")
        label.font = UIFont.systemFont(ofSize: 16, weight: .medium)
        return label
    }()
    /// 密码控制
    lazy var secureButton: UIButton = {
        let button = UIButton(type: .custom)
        button.frame = CGRect(x: self.view.frame.size.width - 50, y: 10.5, width: 45, height: 45)
        button.setImage(UIImage(name: "zl_safe_eye_close"), for: .normal)
        button.setImage(UIImage(name: "zl_safe_eye_open"), for: .selected)
        button.addTarget(self, action: #selector(secureButtonAction), for: .touchUpInside)
        return button
    }()
    override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
        super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
        self.modalPresentationStyle = .overFullScreen
        self.view.backgroundColor = UIColor.clear
    }
    /// 安全码可视控制
    @objc func secureButtonAction() {
        self.secureButton.isSelected = !self.secureButton.isSelected
        self.showPwd()
    }
    @discardableResult
    public class func show(vc: UIViewController? = UIApplication.shared.windows.first?.rootViewController, complete: @escaping KDSafePWDBlock) -> ZLSafeCodeKeyboard {
        let keyboardVC = ZLSafeCodeKeyboard()
        keyboardVC.complete = complete
        vc?.present(keyboardVC, animated: false)
        return keyboardVC
    }
    
    public override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        UIView.animate(withDuration: 0.25) {
            self.view.backgroundColor = UIColor.init(white: 0, alpha: 0.6)
            self.bottomView.frame = CGRect(x: 0, y: self.view.frame.size.height - 376, width: self.view.frame.size.width, height: 376)
        }
    }
    /// 数字点击
    @objc func numberAction(_ button: UIButton) {
        let number = String(button.tag)
        if self.pwd.count == 6 {
            return
        }
        self.pwd = self.pwd + number
        self.showPwd()
    }
    /// 删除
    @objc func delButtonAction() {
        if self.pwd.count == 0 {
            return
        }
        self.pwd.removeLast()
        self.showPwd()
    }
    /// 确定
    @objc func submitButtonAction() {
        let dismiss = self.complete?(self.pwd) ?? false
        if dismiss {
            self.dismiss()
        }
    }
    /// 返回
    @objc func backButtonAction() {
        self.dismiss()
    }
    /// 显示密码
    func showPwd() {
        for i in 0..<6 {
            let tag = i + 100
            guard let label = self.bottomView.viewWithTag(tag) as? UILabel else { continue }
            var number = ""
            if i < self.pwd.count {
                let startIndex = self.pwd.index(self.pwd.startIndex, offsetBy: i)
                let endIndex = self.pwd.index(self.pwd.startIndex, offsetBy: i + 1)
                number = String(self.pwd[startIndex..<endIndex])
                label.text = self.secureButton.isSelected ? number : "*"
            } else {
                label.text = ""
            }
        }
    }
    /// 返回
    @objc func dismiss() {
        UIView.animate(withDuration: 0.25) {
            self.view.backgroundColor = UIColor.clear
            self.bottomView.frame = CGRect(x: 0, y: self.view.frame.size.height, width: self.view.frame.size.width, height: 376)
        } completion: { success in
            self.dismiss(animated: false)
        }
    }
    
    public override func viewDidLoad() {
        super.viewDidLoad()
        self.view.addSubview(self.bottomView)
        self.bottomView.addSubview(self.titleLabel)
        self.bottomView.addSubview(self.secureButton)
        /// 密码
        var top = 71.0
        let gap = 7.0
        var width = ceil((self.view.frame.size.width - gap * 7) / 6.0)
        var left = gap
        for i in 0..<6 {
            let label = self.getPwdLabel()
            label.frame = CGRect(x: left, y: top, width: width, height: 62)
            label.tag = i + 100
            self.bottomView.addSubview(label)
            left = left + gap + width
        }
        /// 密码按钮
        width = ceil((self.view.frame.size.width - gap * 5) / 4.0)
        left = gap
        top = 140.0
        for i in 0..<9 {
            let button = self.getNumberButton(title: String(i + 1))
            button.tag = i + 1
            button.frame = CGRect(x: left, y: top, width: width, height: 44)
            button.addTarget(self, action: #selector(numberAction(_:)), for: .touchUpInside)
            self.bottomView.addSubview(button)
            left = left + gap + width
            if button.tag % 3 == 0 {
                left = gap
                top = top + 44 + gap
            }
        }
        /// 0
        let zeroButton = self.getNumberButton(title: "0")
        zeroButton.tag = 0
        zeroButton.frame = CGRect(x: gap, y: top, width: width * 2 + gap, height: 44)
        zeroButton.addTarget(self, action: #selector(numberAction(_:)), for: .touchUpInside)
        self.bottomView.addSubview(zeroButton)
        /// 返回
        let backButton = self.getNumberButton(title: "")
        backButton.frame = CGRect(x: CGRectGetMaxX(zeroButton.frame) + gap, y: top, width: width, height: 44)
        backButton.setImage(UIImage(name: "zl_safe_pwd_back"), for: .normal)
        backButton.addTarget(self, action: #selector(backButtonAction), for: .touchUpInside)
        self.bottomView.addSubview(backButton)
        /// 删除
        let delButton = self.getNumberButton(title: "")
        delButton.frame = CGRect(x: self.view.frame.size.width - width - gap, y: 140, width: width, height: 44)
        delButton.setImage(UIImage(name: "zl_safe_pwd_del"), for: .normal)
        delButton.addTarget(self, action: #selector(delButtonAction), for: .touchUpInside)
        self.bottomView.addSubview(delButton)
        /// 确定
        let submitButton = self.getNumberButton(title: "确定")
        submitButton.frame = CGRect(x: self.view.frame.size.width - width - gap, y: CGRectGetMaxY(delButton.frame) + gap, width: width, height: 146)
        submitButton.backgroundColor = UIColor.init(hex: "#285AFF")
        submitButton.setTitleColor(UIColor.white, for: .normal)
        submitButton.setTitleColor(UIColor.white, for: .highlighted)
        submitButton.titleLabel?.font = UIFont.systemFont(ofSize: 15, weight: .medium)
        submitButton.addTarget(self, action: #selector(submitButtonAction), for: .touchUpInside)
        self.bottomView.addSubview(submitButton)
    }
    /// 密码
    func getPwdLabel() -> UILabel {
        let label = UILabel()
        label.layer.cornerRadius = 3
        label.layer.masksToBounds = true
        label.textAlignment = .center
        label.textColor = UIColor.init(hex: "#030303")
        label.font = UIFont.systemFont(ofSize: 20, weight: .medium)
        label.backgroundColor = UIColor.init(hex: "#F6F7FB")
        return label
    }
    /// 密码数字按钮
    func getNumberButton(title: String) -> UIButton {
        let button = UIButton(type: .custom)
        button.layer.cornerRadius = 3
        button.layer.masksToBounds = true
        button.setTitle(title, for: .normal)
        button.backgroundColor = UIColor.init(hex:"#F6F7FB")
        button.setTitleColor(UIColor.init(hex:"#030303"), for: .normal)
        button.setTitleColor(UIColor.init(hex:"#030303"), for: .highlighted)
        button.titleLabel?.font = UIFont.systemFont(ofSize: 20, weight: .medium)
        return button
    }
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

extension UIColor {
    convenience init(hex: String, alpha: CGFloat = 1.0) {
        var cStr = hex.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines).uppercased() as NSString;
        
        if(cStr.length < 6){
            self.init(white: 0, alpha: 0)
            return
        }
        
        if(cStr.hasPrefix("0x")){
            cStr = cStr.substring(from: 2) as NSString
        }
        
        if(cStr.hasPrefix("#")){
            cStr = cStr.substring(from: 1) as NSString
        }
        
        if(cStr.length != 6){
            self.init(white: 0, alpha: 0)
            return
        }
        
        let rStr = (cStr as NSString).substring(to: 2)
        let gStr = ((cStr as NSString).substring(from: 2) as NSString).substring(to: 2)
        let bStr = ((cStr as NSString).substring(from: 4) as NSString).substring(to: 2)
        
        var r: UInt32 = 0x0
        var g: UInt32 = 0x0
        var b: UInt32 = 0x0
        
        Scanner.init(string: rStr).scanHexInt32(&r)
        Scanner.init(string: gStr).scanHexInt32(&g)
        Scanner.init(string: bStr).scanHexInt32(&b)
        
        self.init(red: CGFloat(r)/255.0, green: CGFloat(g)/255.0, blue: CGFloat(b)/255.0, alpha: alpha)
    }
}

extension UIImage {
    convenience init?(name: String) {
        var imageBundle = Bundle(for: ZLSafeCodeKeyboard.self)
        if let resourcePath = imageBundle.path(forResource: "ZLSafeCodeKeyboard", ofType: "bundle") {
            if let resourcesBundle = Bundle(path: resourcePath) {
                imageBundle = resourcesBundle
            }
        }
        self.init(named: name, in: imageBundle, compatibleWith: nil)
    }
}
